<template>
  <basic-container>
    <div class="userManage">
      <div class="um-l" :key="treeKey">
        <el-input
            size="small"
            placeholder="请输入内容……"
            v-model="filterText"
        ></el-input>

        <div style="height: 10px; width: 100%"></div>

        <el-tree
            :data="treeData"
            :props="defaultProps"
            default-expand-all
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
            ref="tree"
        ></el-tree>
      </div>
      <div class="um-r">
        <div>
          <m-s-search
              @searchClick="
              (v) => {
                (queryForm = v), getList();
              }
            "
              :list="option.column"
          >
          </m-s-search>
        </div>
        <avue-crud
            :option="option"
            :data="tableData"
            ref="crud"
            @selection-change="selectionChange"
            :page.sync="page"
            @current-change="currentChange"
            @size-change="sizeChange"
        >
          <template slot="menuLeft">
            <el-button
                size="small"
                type="primary"
                @click="
                addToTabsList(
                  '用户',
                  { oid: -1, orgPid: depatId },
                  'userManageTemp',
                  'open'
                )
              "
            >新增
            </el-button>
            <el-button size="small" @click="batchDel()">删除</el-button>
            <el-button size="small" @click="resetData()">重置</el-button>
            <el-button size="small" @click="dispatchApp()">分配应用</el-button>
            <el-button size="small" @click="addToTabsList('用户',{ oid: -1},'userManageFileTemp','new')">
              导入
            </el-button>
            <!--            <el-upload
                          class="upload-wrap"
                          style="display: inline-block"
                          action="/"
                          :http-request="handleHttpRequest"
                          accept="xlsx, xls"
                          :show-file-list="false"
                        >
                          <el-button size="small">用户导入</el-button>
                        </el-upload>-->
          </template>
          <template slot="lockFlag" slot-scope="scope">
            <avue-switch
                :value="scope.row.lockFlag == 0 ? true : false"
                @click="rowState(scope.row)"
            ></avue-switch>
          </template>
          <!-- <template slot="classification" slot-scope="scope">
            <span>{{ getClassification(scope.row.classification) }}</span>
          </template> -->
          <template slot="sex" slot-scope="scope">
            <span>{{
                getSexValue(scope.row.sex)
              }}</span>
          </template>
          <template slot="classification" slot-scope="scope">
            <span>{{
                getValue("classification", scope.row.classification)
              }}</span>
          </template>
          <template slot="position" slot-scope="scope">
            <span>{{ getValue("position", scope.row.position) }}</span>
          </template>
          <template slot="menu" slot-scope="{ row }">
            <el-popover placement="top" width="280" trigger="click">
              <el-row :gutter="10">
                <el-col :span="16"
                >
                  <el-input type="password" v-model="row.password"
                  />
                </el-col>
                <el-col :span="8">
                  <el-button @click="changePasword(row)"
                  >确定
                  </el-button
                  >
                </el-col
                >
              </el-row>
              <el-button
                  slot="reference"
                  type="text"
                  :style="{ marginRight: '10px' }"
              >密码
              </el-button
              >
            </el-popover>
            <el-button
                type="text"
                @click="addToTabsList('用户', row, 'userManageTemp', 'edit')"
            >
              编辑
            </el-button>
            <el-button type="text" @click="del(row)">删除</el-button>
          </template>
        </avue-crud>
      </div>
      <ms-drawer
          @refresh="getList()"
          :visible.sync="visible"
          :tab-list.sync="tabsList"
      ></ms-drawer>
      <el-dialog title="分配应用" :visible.sync="appVisible" append-to-body>
        <div class="dialogBody">
          <el-form ref="dialogForm" label-width="80px" :model="dialogForm">
            <el-form-item label="应用：">
              <el-select v-model="selectedApp" multiple>
                <template v-for="{ nameCn, oid } in applicationList">
                  <el-option
                      :label="nameCn"
                      :key="oid"
                      :value="oid"
                  ></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer">
          <el-button size="small" type="primary" @click="saveBind"
          >确定
          </el-button
          >
          <el-button size="small" @click="appVisible = false">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </basic-container>
</template>

<script>
import * as api from "@/api/userManage/index";
import * as application from "@/api/application";
import * as common from "@/api/common";
import MSSearch from "@/DMDComponents/MSSearch.vue";

export default {
  name: "userManage",
  components: {MSSearch},
  data() {
    return {
      queryForm: {},
      filterText: "",
      treeKey: 1,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      depatId: "", // 左侧树选中的部门
      treeData: [],
      tabsList: [],
      defaultProps: {
        children: "children",
        label: "nameCn",
      },

      tableData: [],
      selectedList: [], // 选择的用户
      selectedApp: [], // 选择的应用
      applicationList: [], // 应用列表
      appVisible: false,
      dialogForm: {},
      option: {
        height: "auto",
        calcHeight: 30,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        selection: true,
        labelWidth: 120,
        menuWidth: 150,
        viewBtn: false,
        dialogClickModal: false,
        tabs: true,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false,
        align: "center",
        column: [
          {
            label: "用户名",
            prop: "username",
            msSearch: true,
          },
          {
            label: "姓名",
            prop: "name",
          },
          {
            label: "性别",
            prop: "sex",
          },
          {
            label: "手机号",
            prop: "phone",
            msSearch: true,
          },

          {
            label: "角色",
            prop: "roleName",
            width: "250"
          },
          {
            label: "职位",
            prop: "position",
          },
          {
            label: "邮箱",
            prop: "mail",
          },
          {
            label: "用户分组",
            prop: "userGroupName",
          },
          {
            label: "分配应用",
            prop: "applicationName",
          },
          {
            label: "启用",
            prop: "lockFlag",
          },
          {
            label: "密级",
            prop: "security",
          },
        ],
        secretData: [],
        positionData: [],
      },

      visible: false,
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    handleHttpRequest(options) {
      const file = options.file;
      // 创建 FormData 对象
      const formData = new FormData();
      // 将文件添加到 FormData 中
      formData.append("file", file);
      formData.append("excelCode", "WDDRUSER");
      formData.append("bizData", "");
      api.uploadUser(formData).then((res) => {
        if (res.data && res.data.success) {
          this.$message.success("上传成功！");
          this.getList();
        } else {
          this.$message.success("上传失败！");
        }
      });
    },
    getSecret() {
      common.getDic("secret").then((res) => {
        this.secretData = res.data.data;
      });
      common.getDic("position").then((res) => {
        this.positionData = res.data.data;
      });
    },
    getSexValue(value) {
      return value === 0 ? "男" : "女"
    },
    getValue(type, value) {
      if (!value) {
        return "";
      }
      let data =
          type === "classification" ? this.secretData : this.positionData;
      if (!data || data.length === 0) {
        return "";
      }
      const [selected] = data.filter((v) => Number(v.value) === Number(value));
      return selected ? selected.name : "";
    },
    saveBind() {
      const userIds = this.selectedList.map((v) => v.pid).join(",");
      if (this.selectedApp.length === 0) {
        this.$message.error("请选择应用！");
        return;
      }
      const applicationIds = this.selectedApp.join(",");
      api
          .allocateApplication({userIds, applicationIds, orgId: this.depatId})
          .then(() => {
            this.$message.success("分配成功");
            this.selectedApp = [];
            this.appVisible = false;
          });
    },
    getApplicationList() {
      application.getlist().then((res) => {
        this.applicationList = res.data.data;
      });
    },
    getClassification(data) {
      if (!data) {
        return "公开";
      }
      return data === 1 ? "一般" : "高级";
    },
    selectionChange(data) {
      this.selectedList = data;
    },
    dispatchApp() {
      if (this.selectedList.length === 0) {
        this.$message.error("请选择用户！");
        return;
      }
      this.appVisible = true;
    },
    resetData() {
      this.treeKey += 1;
      if (this.treeKey > 1000) {
        this.treeKey = 1;
      }
      this.handleNodeClick("");
    },
    batchDel() {
      if (this.selectedList.length === 0) {
        this.$message.error("请选择用户！");
        return;
      }
      const idArr = this.selectedList.map((v) => v.pid);
      this.$confirm("是否删除？").then(() => {
        api.batchDelUser(idArr).then(() => {
          this.$message.success("删除成功");
          this.getList();
        });
      });
    },
    changePasword(data) {
      const {pid, password} = data;
      const paramsData = {
        pid,
        password,
      };
      api.updatePassword(paramsData).then(() => {
        this.$message.success("更新成功");
        this.$refs.crud.$el.click();
        this.getList();
      });
    },
    rowState(data) {
      const {pid, lockFlag} = data;
      const paramsData = {
        pid,
        lockFlag: lockFlag === 0 ? 1 : 0,
      };
      api.updateLockFlag(paramsData).then(() => {
        this.$message.success("更新成功");
        this.$refs.crud.$el.click();
        this.getList();
      });
    },
    del(row) {
      this.$confirm("是否删除？").then(() => {
        api.delUser({pid: row.pid}).then(() => {
          this.$message.success("删除成功");
          this.getList();
        });
      });
    },
    handleNodeClick(data) {
      this.depatId = data.pid;
      this.page = {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      };
      this.getList();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    addToTabsList(title, row, component, type) {
      let ids = this.tabsList.map(
          (item) => item.row.oid + "-" + item.component
      );
      if (!ids.includes(row.oid + "-" + component)) {
        this.tabsList.push({title, row, component, type});
      }
      this.visible = true;
    },
    getList() {
      const params = {
        current: this.page.currentPage,
        size: this.page.pageSize,
        ...this.queryForm,
      };
      if (this.depatId) {
        params.orgPid = this.depatId;
      }
      api.getUserList({...params}).then((res) => {
        this.tableData = res.data.data.list;
        this.page.total = res.data.data.totalRows;
      });
    },
    getUserTree() {
      api.getUserTree().then((res) => {
        let data = res.data.data;
        this.treeData = data;
        // this.depatId = data[0].pid;
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.getList();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList();
    },
  },
  mounted() {
    this.depatId = "";
    this.getUserTree();
    this.getList();

    this.getSecret();
    this.getApplicationList();
  },
};
</script>

<style scoped lang="scss">
.userManage {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  flex-wrap: nowrap;

  > div {
    height: 100%;
  }

  .um-l {
    width: 300px;
  }

  .um-r {
    width: calc(100% - 320px);
  }
}

.dialogBody {
  padding-top: 20px;
  min-height: 300px;
}

::v-deep .el-tree {
  height: calc(100% - 50px);
  overflow-y: scroll;
}
</style>
